package Controller.Hadoop;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import Bean.areaGGLBean;
import Bean.areaGSLBean;
import Bean.arealikeBean;
import Bean.monthGLBean;
import Bean.musicALBean;
import Bean.musicGLBean;
import Bean.singerALBean;
import Dao.adminDao;

public class hadoopareaGSJar implements Controller {
	private adminDao dao;
	private areaGSLBean bean = new areaGSLBean();

	public void setDao(adminDao dao) {
		this.dao = dao;
	}

	@SuppressWarnings("null")
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse arg1) throws Exception {

		String[] cmd = {
				"hadoop jar /home/hadoop/Lab/areaGS.jar /bigmusic.csv /areaGS",
				"hadoop fs -cat /areaGS/result.csv" };

		System.out.println("하둡 연결");
		hadoopConect hadoop = new hadoopConect();
		System.out.println("하둡 시작");
		// System.out.println(command.get(selectCom)+"하둡 명령어");
		System.out.println(cmd[0]);
		List<String> ret = hadoop.exec(cmd[0]);

		int success = 0;
		String result = "끝";

		for (int i = 0; i < ret.size(); i++) {
			String test = ret.get(i);
			success = test.indexOf("successfully");
			if(success > -1){
				result = "지역 성별 가수 선호<br> 통계 처리 완료";
			}
		}
		System.out.println("하둡 끝 ");

		System.out.println(result);

		hadoop = new hadoopConect();
		List<String> retDB = hadoop.exec(cmd[1]);
		System.out.println(cmd[1]);

		dao.deleteAreaGSLAll();

		for (int i = 0; i < retDB.size(); i++) {
			String test = retDB.get(i);
			String[] oneline = null;
			if (test != null) {
				oneline = test.split("\r\n");
			}
			for (String string : oneline) {
				String[] DBcolum = string.trim().split(",");
				
				bean.setAgsl_area(Integer.parseInt(DBcolum[0]));
				bean.setAgsl_gender(Integer.parseInt(DBcolum[1]));
				bean.setAgsl_singer(Integer.parseInt(DBcolum[2]));
				bean.setAgsl_count(Integer.parseInt(DBcolum[3]));	
				
				dao.insertAreaGSL(bean);
			}
		}

		System.out.println("DB 끝");

		ModelAndView mav = new ModelAndView();
		mav.setViewName("hadoopResult");
		mav.addObject("result", result);
		return mav;
	}
}
